﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Reflection;
using System.Collections;


    public class StringUtility
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="uncompressedString"></param>
        /// <returns></returns>
        public static string Compress(string uncompressedString)
        {
            //byte[] bytData = System.Text.Encoding.UTF8.GetBytes(uncompressedString);
            //MemoryStream ms = new MemoryStream();
            //Stream s = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
            //s.Write(bytData, 0, bytData.Length);
            //s.Close();
            //byte[] compressedData = (byte[])ms.ToArray();
            //return System.Convert.ToBase64String(compressedData, 0, compressedData.Length).Replace("+", "%2B");//替换+，否则在服务器解码的时候会出错
            return null;
        }
        /// <summary>
        /// 解压 
        /// </summary>
        /// <param name="compressedString"></param>
        /// <returns></returns>  
        public static string DeCompress(string compressedString)
        {
        //    System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder();
        //    int totalLength = 0;

        //    compressedString = compressedString.Replace("+", "%2B");//替换+，否则在服务器解码的时候会出错
        //    compressedString = HttpUtility.UrlDecode(compressedString);
        //    Stream s2 = null;
        //    try
        //    {
        //        byte[] bytInput = System.Convert.FromBase64String(compressedString); ;
        //        byte[] writeData = new byte[4096];
        //        s2 = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(new MemoryStream(bytInput));

        //        while (true)
        //        {
        //            int size = s2.Read(writeData, 0, writeData.Length);
        //            if (size > 0)
        //            {
        //                totalLength += size;
        //                uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData, 0, size));
        //            }
        //            else
        //            {
        //                break;
        //            }
        //        }
        //    }
        //    catch
        //    { }
        //    finally
        //    {
        //        if (s2 != null)
        //        {
        //            s2.Close();
        //        }
        //    }
        //    return uncompressedString.ToString();
            return null;
        }

        /// <summary>
        /// 对象转换成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ConvertObjectToString<T>(T obj)
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            object[] array = new object[properties.Length];
            string strSearchword = "";
            for (int i = 0; i < properties.Length; i++)
            {
                if (strSearchword.Length > 0) strSearchword += ";";

                if (!string.IsNullOrEmpty(properties[i].Name))
                {
                    strSearchword += properties[i].Name + ":" + properties[i].GetValue(obj, null); ;
                }
            }
            return strSearchword;
        }

        /// <summary>
        /// 字符串还原成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T ConvertStringToObject<T>(string str) where T : new()
        {
            Hashtable htValues = ConvertStringToHashtable(str);
            //此处可作安全检查 
            //TODO:
            if (htValues.Count == 0)
            {
                //空值
                return default(T);
            }

            //构造泛型实体
            T result = new T();
            //获得泛型类型
            Type t = typeof(T);
            //属性集合
            PropertyInfo[] properties = t.GetProperties();
            //属性赋值
            foreach (var item in properties)
            {
                //字符串
                if (item.PropertyType == typeof(string))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).String, null);
                }
                //整数（不可空）
                if (item.PropertyType == typeof(int))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToInt32 ?? 0, null);
                }
                //整数（可空）
                if (item.PropertyType == typeof(int?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToInt32, null);
                }
                //布尔（不可空）
                if (item.PropertyType == typeof(bool))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToBool ?? false, null);
                }
                //布尔（可空）
                if (item.PropertyType == typeof(bool?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToBool, null);
                }
                //时间（不可空）
                if (item.PropertyType == typeof(DateTime))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToDateTime.GetValueOrDefault(DateTime.Now), null);
                }
                //时间（可空）
                if (item.PropertyType == typeof(DateTime?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToDateTime, null);
                }
                //实数（不可空）
                if (item.PropertyType == typeof(double))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToDouble.Value, null);
                }
                //实数（可空）
                if (item.PropertyType == typeof(double?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToDouble, null);
                }
                //十进制实数（不可空）
                if (item.PropertyType == typeof(decimal))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToDecimal.Value, null);
                }
                //十进制实数（可空）
                if (item.PropertyType == typeof(decimal?))
                {
                    item.SetValue(result, new HZ.Common.ConvertHelper(htValues[item.Name]).ToDecimal, null);
                }
            }
            return result;
        }

        /// <summary>
        /// 字符串转换成Hash表
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static Hashtable ConvertStringToHashtable(string str)
        {
            string[] strArray1 = str.Split(new char[] { ';' });
            Hashtable htValues = new Hashtable();

            string[] strArray2 = new string[2];
            for (int i = 0; i < strArray1.Length; i++)
            {
                strArray2 = strArray1[i].Split(new char[] { ':' });
                if (strArray2.Length >= 2 && !string.IsNullOrEmpty(strArray2[0]))
                {
                    htValues.Add(strArray2[0], strArray2[1]);
                }
            }
            return htValues;
        }
/// <summary>
///  自定义拼接IList某列数据
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="tlist"> 需要拼接的IList</param>
/// <param name="fieldname">列名</param>
/// <param name="splitstring">分割符</param>
/// <param name="usequot">是否使用单引号包含值</param>
/// <returns>返回拼接后字符串</returns>
        public static string GetModelFieldArrayString<T> ( IList<T> tlist, string fieldname, string splitstring, bool usequot )
        {
            Type type = typeof (T);
            PropertyInfo property = type.GetProperty (fieldname);
            if(property == null)
            {
                throw new ArgumentException ("fieldname", "");

            }

            if(!usequot || property.PropertyType != typeof (string))
            {
                System.Text.StringBuilder result = new System.Text.StringBuilder (512);
                for(int i = 0; i < tlist.Count; i++)
                {
                    if(i == 0)
                    {
                        result.Append (property.GetValue (tlist[i], null));
                    }
                    else
                    {
                        result.AppendFormat ("{0}{1}", splitstring, property.GetValue (tlist[i], null).ToString ().Replace (splitstring, " "));
                    }

                }
                return result.ToString ();
            }
            else
            {
                System.Text.StringBuilder result = new System.Text.StringBuilder (512);
                for(int i = 0; i < tlist.Count; i++)
                {
                    if(i == 0)
                    {
                        result.AppendFormat ("'{0}'", property.GetValue (tlist[i], null));
                    }
                    else
                    {
                        result.AppendFormat ("{0}'{1}'", splitstring, property.GetValue (tlist[i], null).ToString ().Replace (splitstring, " "));
                    }

                }
                return result.ToString ();
            }


        }


    }
